package main

import (
	"encoding/json"
	"fmt"
	"tempSend/models"
	"tempSend/pkg/cache"
	"tempSend/pkg/database"

	"tempSend/pkg/gopool"
	"tempSend/pkg/logging"
	"tempSend/pkg/util"

	"tempSend/pkg/xcx"
	"time"

	"github.com/medivhzhan/weapp/message/template"
)

func main() {
	defer destroyHander()
	util.SetMpID(1)

	ready(10)
	deal(10, 10)
}

//销毁句柄
func destroyHander() {
	database.Close()
	cache.Close()
}

var tempmsg_wait_key string = "tempmsg_wait"

//准备消费数据
//push_num 要推送的数据
func ready(push_num int) {
	//获取七天内要推送的数据
	data := models.GetTemplateMsg(push_num)
	count := len(data)

	var need_send_ids []int

	if count > 0 {
		for i := 0; i < count; i++ {
			key := "tempmsg_user:" + data[i].Openid
			if _, err := cache.Get(key); err == nil {
				//24小时内已经推送过了
				continue
			} else {
				//加入等待发送队列
				json, _ := json.Marshal(data[i])
				cache.Lpush(tempmsg_wait_key, json)
				need_send_ids = append(need_send_ids, data[i].ID)
			}
		}
	}

	//设置待推送的数据状态为推送中
	if len(need_send_ids) > 0 {
		models.SetTemplateMsgStatus(need_send_ids, models.SENDING)
	}
}

//处理队列中的数据
//push_num int 推送数量
//run_goroutine_num int 启动的线程数量
func deal(push_num, run_goroutine_num int) {
	//生成本次消费日志
	logging.TempLogInit()

	pool := gopool.NewGoPool(run_goroutine_num)
	//获取模板
	template := template.Message{
		"keyword1": map[string]string{
			"value": "端午节到了！",
			"color": "#ca0c16",
		},
		"keyword2": time.Now().Format("20160102"),
		"keyword3": "端午节马上要到了，把祝福、健康、快乐传递给朋友和亲人【点击接受祝福】",
	}

	//获取推送的模板id
	mpInfo := models.GetMpInfo()
	if mpInfo.ID <= 0 {
		logging.Fatal("mpinfo not fount")
		return
	}
	var template_id string = mpInfo.TemplateId
	//page
	page := "..."
	//存储要发送用户的openid，formid
	channel := make(chan models.Template)

	go func(template_id string, page string) {
		user_info := models.Template{}
		user_info.Template_id = template_id
		user_info.Page = page
		var tempmsg interface{}
		for i := 0; i < push_num; i++ {
			tempmsg = new(interface{})
			tempmsg, _ = cache.Rpop(tempmsg_wait_key)
			if tempmsg == "" {
				break
			}

			json.Unmarshal([]byte(fmt.Sprintf("%s", tempmsg)), &user_info)

			key := "tempmsg_user:" + user_info.Openid
			is_exit := cache.Exit(key)

			if is_exit == true {
				continue
			} else {
				fmt.Println(key)
				//设置他为发送状态
				cache.Set(key, "1", 24*time.Hour)
			}

			channel <- user_info
		}
		//结束-关闭通道
		close(channel)

	}(template_id, page)

	for user_info := range channel {
		pool.Add(1)
		go func(info models.Template) {
			//模板推送
			err := xcx.SendTemplate(info.Openid, info.Template_id, info.Page, info.FormId, template)
			//记录log
			logging.TempSuccess(err)
			//对数据进行分组
			pool.Done()
		}(user_info)
	}

	//推送完成
	pool.Wait()
	fmt.Println("Ok")
}
